package com.cskaoyan.gateway.controller.user;

import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.IRegisterService;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.KaptchaCodeRequest;
import com.mall.user.dto.KaptchaCodeResponse;
import com.mall.user.dto.UserRegisterRequest;
import com.mall.user.dto.UserRegisterResponse;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @ClassName: RegisterController
 * @Author: 南风
 * @Email: 1480207032@qq.com
 * @Description:
 * @Date: 2020/7/11 16:10
 */
@RestController
@RequestMapping("user")
@Anoymous
public class RegisterController {
    @Reference
    private IKaptchaService kaptchaService;

    @Reference
    private IRegisterService registerService;

    @PostMapping("register")
    public ResponseData register(@RequestBody Map<String, String> map,
                                 HttpServletRequest request){
        String userName = map.get("userName");
        String userPwd = map.get("userPwd");
        // code
        String captcha = map.get("captcha");
        String email = map.get("email");

        // 1、验证验证码，kaptcha_uuid + code
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        // kaptcha_uuid
        String kaptcha_uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(kaptcha_uuid);
        kaptchaCodeRequest.setCode(captcha);

        KaptchaCodeResponse kaptchaCodeResponse = kaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        String code = kaptchaCodeResponse.getCode();
        if (!code.equals(SysRetCodeConstants.SUCCESS.getCode())){
            // 验证失败
            return new ResponseUtil<>().setErrorMsg(kaptchaCodeResponse.getMsg());
        }

        // 2、向相关数据表插入数据
        UserRegisterRequest registerRequest = new UserRegisterRequest();
        registerRequest.setUserName(userName);
        registerRequest.setUserPwd(userPwd);
        registerRequest.setEmail(email);

        UserRegisterResponse userRegisterResponse = registerService.register(registerRequest);
        if (userRegisterResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(null);
        }
        return new ResponseUtil<>().setErrorMsg(userRegisterResponse.getMsg());
    }
}
